#include "epoll_reactor.h"
#include "ihandle.h"
#include <unistd.h>

EpollReactor::EpollReactor()
: mEpoll(epoll_create(1024)) {
}

EpollReactor::~EpollReactor() {
    close(mEpoll);
}

void EpollReactor::RegisterHandle(IHandle* h, int event) {
    struct epoll_event ee;
    ee.data.ptr = h;
    ee.events = event;
    epoll_ctl(mEpoll, EPOLL_CTL_ADD, h->GetSock(), &ee);
}

void EpollReactor::RemoveHandle(IHandle* h) {
    epoll_ctl(mEpoll, EPOLL_CTL_DEL, h->GetSock(), nullptr);
}

void EpollReactor::HandleEvents(int milliseconds) {
    struct epoll_event ees[256];
    int nfds = epoll_wait(mEpoll, ees, 256, milliseconds);
    for (int i = 0; i < nfds; i++) {
        struct epoll_event& ee = ees[i];
        IHandle* h = (IHandle*)ee.data.ptr;
        if (ee.events & EPOLLIN) {
            h->OnIn();
        }
        if (ee.events & EPOLLOUT) {
            h->OnOut();
        }
    }
}
